package com.tool.sqlexecutor.sql;

import com.tool.sqlexecutor.config.DataSourceProperty;
import org.springframework.core.io.Resource;

import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

public class MultiDataSourceExecutor {
    private final String separator;
    private final Resource resource;
    private List<DataSourceProperty> dataSourceProperties;
    private ExecutorService executorService = new ThreadPoolExecutor(5, 5,
            0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());


    public MultiDataSourceExecutor(List<DataSourceProperty> dataSourceProperties, Resource resource, String separator) {
        this.dataSourceProperties = dataSourceProperties;
        this.resource = resource;
        this.separator = separator;
    }

    public String run() throws InterruptedException {
        List<SqlExecutor> sqlExecutors = dataSourceProperties
                .stream()
                .map(dataSourceProperty -> new SqlExecutor(dataSourceProperty, resource, separator))
                .collect(Collectors.toList());
        List<Future<String>> futures = executorService.invokeAll(sqlExecutors);
        String result = futures.stream()
                .map(f -> getExecuteResult(f))
                .collect(Collectors.joining("\n"));
        executorService.shutdown();
        return result;
    }

    private String getExecuteResult(Future<String> f) {
        try {
            return f.get();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}
